<template>
<div class="adoptList">
  <search-block type="flex">
    <el-form inline :model="search">
      <el-form-item label="名称:">
        <el-input v-model="search.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="品种:">
        <el-cascader
          v-model="varietyVal"
          clearable
          :options="cateData"
          :props="{
            label: 'cateName',
            value: 'cateCode'
          }"></el-cascader>
      </el-form-item>
      <el-form-item label="是否启用:">
        <el-select v-model="search.enableFlag" clearable>
          <el-option label="启用" value="1"></el-option>
          <el-option label="未启用" value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="adopt-buttons">
      <el-button @click="resetSearch">重置</el-button>
      <el-button type="primary" @click="searchTable(true)">查询</el-button>
      <el-button type="primary" @click="() => addAdopt()">添加</el-button>
      <comments-switch
          comment-business-type="1"></comments-switch>
    </div>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="imgUrl" label="图标" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <img v-if="row.imgUrl" style="height: 60px" :src="generateMediaUrl({fileOpenUrl: row.imgUrl})"/>
      </template>
    </el-table-column>
    <el-table-column slot="name" label="名称" align="center" header-align="center" min-width="210">
      <template v-slot="{row}">
        {{row.name + (row.memo ? '(' + row.memo + ')' : '')}}
      </template>
    </el-table-column>
    <el-table-column slot="price" label="价格" align="center" header-align="center" width="180">
      <template v-slot="{row}">
        {{generatePrice(row)}}
      </template>
    </el-table-column>
    <el-table-column slot="variety" label="品种" align="center" header-align="center" min-width="105">
      <template v-slot="{row}">
        {{getVarietyName(row.kind, row.variety)}}
      </template>
    </el-table-column>
    <el-table-column slot="limitedDate" label="截止日期" align="center" header-align="center" width="120">
      <template v-slot="{row}">
        <div v-html="alarmDate(row.limitedDate)"></div>
      </template>
    </el-table-column>
    <el-table-column slot="SKU" label="库存" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-button type="primary" icon="el-icon-edit" circle @click="showSku(row)"></el-button>
      </template>
    </el-table-column>
    <el-table-column slot="enableFlag" label="启用" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-popconfirm
            :title="row.enableFlag === '1' ? `是否确认禁用？` : `是否确认启用？`"
            @confirm="doEnable(row, row.enableFlag === '0')"
        >
          <el-switch
            disabled
            slot="reference"
            v-model="row.enableFlag"
            active-value="1"
            inactive-value="0"></el-switch>
        </el-popconfirm>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="190" fixed="right">
      <template v-slot="{row}">
        <div class="wrap-table-buttons">
          <el-button size="mini" @click="showDetails(row)">预览详情</el-button>
          <el-button type="primary" size="mini" @click="editAdopt(row)" style="width:80px" v-if="row.enableFlag === '0'">编辑</el-button>
          <el-button size="mini" @click="viewAdopt(row)" style="width:80px" v-else>查看</el-button>
          <el-button size="mini" @click="showHarvest(row)">预览成品</el-button>
          <el-popconfirm
            v-if="row.enableFlag === '0' && row.lockStatus !== '1'"
            title="是否确认删除该商品？"
            @confirm="delAdopt(row)">
            <el-button slot="reference" type="danger" size="mini" style="width:80px">删除</el-button>
          </el-popconfirm>
          <el-button size="mini" @click="showComment(row)">查看评论</el-button>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <el-drawer
    :key="refreshKey"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    :size="1000"
    :wrapperClosable="false"
    destroy-on-close>
    <adopt-details
      :adopt-id.sync="forms.adoptId"
      :lock-status="forms.lockStatus"
      :is-view="forms.formsType === 'VIEW'"
      @success="searchTable(forms.formsType === 'ADD')"
      @close="closeDrawer">
    </adopt-details>
  </el-drawer>
  <el-dialog
    :visible.sync="watchDetails.show"
    title="详情预览"
    @open="getDetails"
    @closed="hideDetails">
    <div class="watch-details ql-editor" v-loading="watchDetails.loading" v-html="watchDetails.content"></div>
  </el-dialog>
  <el-dialog
    :visible.sync="searchSku.show"
    width="800px"
    v-if="searchSku.show"
    class="force-inner-scroll"
    :title="'编辑库存' + (searchSku.row ? `【${searchSku.row.name}】` : '')">
    <adopt-s-k-u :adoptId="searchSku.row ? searchSku.row.id : ''" :is-dialog="true"></adopt-s-k-u>
  </el-dialog>
  <el-dialog
    :visible.sync="harvestForms.showForm"
    :title="`【${harvestForms.row.name}】收获物信息`"
    destroy-on-close
    width="900px"
    @opened="onOpenHarvestPerson"
    @close="hideHarvestPerson">
    <y-table
      ref="harvestTable"
      border
      :getDataWay="harvestDataWay"
      :columns="harvestColumns">
      <el-table-column slot="productPic" label="图标" align="center" header-align="center" width="85">
        <template v-slot="{row}">
          <img v-if="row.productPic" style="height: 40px;width: 40px" :src="generateMediaUrl({fileOpenUrl: row.productPic})"/>
        </template>
      </el-table-column>
      <el-table-column slot="productCategoryId" label="成品类别" align="center" header-align="center" width="250">
        <template v-slot="{row}">
          <div v-for="item in row.productCategoryId.split(',').filter(s => s.indexOf(harvestForms.row.productCateId) >= 0 )" :key="item">
            {{getCateNameById(item)}}
          </div>
        </template>
      </el-table-column>
    </y-table>
  </el-dialog>
  <el-dialog
    v-if="commentForms.row"
    :key="commentRefreshKey"
    width="1200px"
    class="force-inner-scroll"
    :visible.sync="commentForms.showForm"
    @closed="commentRefreshKey += 2"
    :title="`物品【${commentForms.row.name}】的评论`">
    <comments-info-list
      v-if="commentForms.row && commentForms.row.id"
      :biz-id="commentForms.row.id"
      comment-business-type="1"></comments-info-list>
  </el-dialog>
</div>
</template>

<script>
import adoptDetails from "./adoptDetails/adoptDetails";
import adoptSKU from "./adoptDetails/adoptSKU";
import CommentsSwitch from "@/components/Comments/CommentsSwitch";
import CommentsInfoList from "@/components/Comments/CommentsInfoList";
export default {
  name: "adoptList",
  components: { CommentsSwitch, CommentsInfoList, adoptDetails, adoptSKU },
  provide(){
    return{
      adoptCateData: () => this.productCateData
    }
  },
  inject: ['generateMediaUrl', 'registerCustomEvent'],
  data(){
    return{
      refreshKey: 0,
      commentRefreshKey: 1,
      search: {
        name: '',
        kind: '',
        variety: '',
        enableFlag: '',
      },
      columns: [{
        label: "商品图标",
        prop: "imgUrl",
        template: true,
      },{
        label: "名称",
        prop: "name",
        template: true
      },{
        label: "价格",
        prop: "price",
        template: true
      },{
        label: "品种",
        prop: "variety",
        template: true
      },{
        label: "截止日期",
        prop: "limitedDate",
        template: true
      },{
        label: "库存",
        prop: "SKU",
        template: true
      },{
        label: "启用",
        prop: "enableFlag",
        template: true
      }],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加',
          'EDIT': '编辑',
          'VIEW': '查看'
        },
        adoptId: null,
        lockStatus: null,
        showForm: false,
      },
      cateData: [],
      productCateData: [],
      watchDetails:{
        row: null,
        show: false,
        content: '',
        loading: false
      },
      searchSku:{
        row: null,
        show: false,
      },
      harvestForms:{
        row: {},
        showForm: false,
      },
      commentForms:{
        row: {},
        showForm: false,
      },
      harvestData: [],
      harvestColumns: [{
        prop: 'productPic',
        template: true
      },{
        prop: 'productCategoryId',
        template: true
      },{
        label: '名称',
        prop: 'productName',
        width: 250
      },{
        label: '货号',
        prop: 'productSn'
      },{
        label: '商品编号',
        prop: 'productSkuCode'
      }]
    }
  },
  computed:{
    getDataWay(){
      return {
        dataType: 'url',
        data: this.$api.adopt.queryAdoptInfoList,
        param: this.search
      }
    },
    harvestDataWay(){
      return {
        data: this.harvestData
      }
    },
    varietyVal:{
      get(){
        let ary = [];
        if(this.search.kind){
          ary.push(this.search.kind);
          if(this.search.variety){
            ary.push(this.search.variety);
          }
        }
        return ary;
      },
      set(val = []){
        val = val || [];
        [this.search.kind = '', this.search.variety = ''] = val;
      }
    }
  },
  created() {
    this.$yAxios({
      url: this.$api.adopt.queryAdoptCategory
    }, info => {
      this.cateData = info;
    });
    this.registerCustomEvent('refreshGoodsClassify', 'adoptList', this.getProductCateData);
    this.getProductCateData();
  },
  methods:{
    resetSearch(){
      Object.keys(this.search).map(key => this.search[key] = '');
    },
    searchTable(jumpToFirst){
      this.$refs['table'].loadData(this.search, jumpToFirst);
    },
    alarmDate(date){
      if(!date) return '';
      //该时间与当前时间相差多少天
      let minus = new Date(date) - new Date();
      let minusDay = minus / (1000*60*60*24);
      if(minusDay < 0) return `<s>${date}</s>`;
      if(minusDay <= 3) return `<span class="y-warning">${date}</span>`;
      else return `<span>${date}</span>`;
    },
    generatePrice(row){
      if(!row.minPrice && !row.maxPrice){
        return '无'
      }else if(!row.minPrice){
        return '￥' + row.maxPrice
      }else if(!row.maxPrice){
        return '￥' + row.minPrice
      }else{
        if(row.minPrice === row.maxPrice){
          return '￥' + row.minPrice
        }else{
          return '￥' + row.minPrice + '~￥' + row.maxPrice
        }
      }
    },
    closeDrawer(){
      this.forms.showForm = false;
      this.refreshKey += 2 ;
    },
    getVarietyName(kind, variety){
      if(!kind || !this.cateData.length) return '';
      let str = ''
      let kindObj = this.cateData.find(cd => cd.cateCode === kind);
      if(!kindObj) return '';
      str += kindObj.cateName;
      if(variety && kindObj.children && kindObj.children.length){
        let varietyObj = kindObj.children.find(vd => vd.cateCode === variety);
        if(varietyObj){
          str += '/' + varietyObj.cateName;
        }
      }
      return str;
    },
    getProductCateData(){
      this.$yAxios({
        url: this.$api.goods.queryCategory,
      }, info => {
        this.productCateData = info;
      })
    },
    //根据categoryId生成name
    getCateNameById(id){
      try{
        let res = [];
        let ids = id.split('/');
        let currentArray = this.productCateData;
        while(ids.length){
          let currentId = ids.shift();
          let current = currentArray.find(item => item.id === currentId)
          res.push(current.name);
          currentArray = current.children;
        }
        if(res.length <= 1){
          return res.toString();
        }else{
          return res.join('/');
        }
      }catch(e){
        return '';
      }
    },
    addAdopt(){
      this.forms.formsType = 'ADD';
      this.forms.adoptId = null;
      this.forms.lockStatus = null;
      this.forms.showForm = true;
    },
    editAdopt(row){
      this.forms.formsType = 'EDIT';
      this.forms.adoptId = row.id;
      this.forms.lockStatus = row.lockStatus;
      this.forms.showForm = true;
    },
    viewAdopt(row){
      this.forms.formsType = 'VIEW';
      this.forms.adoptId = row.id;
      this.forms.lockStatus = row.lockStatus;
      this.forms.showForm = true;
    },
    delAdopt(row){
      this.$yAxios({
        url: this.$api.adopt.removeAdoptInfo,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.searchTable();
      })
    },
    doEnable(row, bool){
      let url = bool ? this.$api.adopt.enableAdopt : this.$api.adopt.disableAdopt;
      this.$yAxios({
        url,
        data:{
          ids: [row.id]
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: bool ? '启用成功' : '禁用成功'
        });
        this.searchTable();
      })
    },
    showDetails(row){
      this.watchDetails.row = row;
      this.watchDetails.show = true;
    },
    hideDetails(){
      this.watchDetails.row = null;
      this.watchDetails.content = '';
    },
    getDetails(){
      this.watchDetails.loading = true;
      this.$yAxios({
        url: this.$api.adopt.selectAdoptImageText,
        data:{
          adoptId: this.watchDetails.row.id
        }
      }, info => {
        this.watchDetails.content = info && info.content ? info.content : '';
        this.watchDetails.loading = false;
      }, e => {
        this.watchDetails.loading = false;
      });
    },
    showSku(row){
      this.searchSku.row= row;
      this.searchSku.show = true;
    },
    showHarvest(row){
      this.harvestForms.row = row;
      this.$nextTick(() => {
        this.harvestForms.showForm = true;
      })
    },
    showComment(row){
      this.commentForms.row = row;
      this.$nextTick(() => {
        this.commentForms.showForm = true;
      })
    },
    onOpenHarvestPerson(){
      this.$yAxios({
        url: this.$api.goods.queryAdoptGoods,
        data:{
          id: this.harvestForms.row.productCateId
        },
        loading: true
      }, info => {
        this.harvestData = info;
      })
    },
    hideHarvestPerson(){
      this.harvestForms.row = {};
      this.harvestData = [];
      this.harvestForms.showForm = false;
    },
  }
}
</script>

<style scoped lang="less">
.adoptList{
  .adopt-buttons{
    flex-shrink: 0;
    >*:not(:first-child){
      margin-left: 10px;
    }
  }
  /deep/ .watch-details{
    min-height: 50vh;
  }
}
</style>
